package cdu.xjj.service.impl;

import cdu.xjj.constants.SecurityConstants;

import cdu.xjj.custom.CustomUserDetails;
import cdu.xjj.pojo.entity.manage.Role;
import cdu.xjj.pojo.entity.manage.User;
import cdu.xjj.repository.manage.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
@RequiredArgsConstructor
public class CustomUserServiceImpl implements UserDetailsService {

    private final UserRepository userRepository;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        User user = userRepository.findByUsername(username);
        Assert.notNull(user, "用户名或密码错误！");
        Set<GrantedAuthority> authorities = new HashSet<>();
        List<Role> roles = user.getRoles();
        // todo 优化代码
        if (roles != null && !roles.isEmpty()) {
            for (Role role : roles) {
                // 添加用户角色信息
                authorities.add(new SimpleGrantedAuthority(SecurityConstants.ROLE_PREFIX + role.getName()));
            }
        }

        // 构造自定义用户详情
        return new CustomUserDetails(user);
    }


}
